<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="600px" @confirm="handleSubmit"
			@close="handleClose">
			<div class="mt-[-28px]">
				<el-card class="!border-none mb-[-16px]" shadow="never">
				    <el-alert type="warning" title="点击选择分组，未选择则不分组" :closable="false" show-icon />
				</el-card>
				<el-card class="!border-none" v-loading="pager.loading" shadow="never">
					<div class="">
						<el-table :data="pager.lists" style="width: 100%" height="260px" highlight-current-row
							@current-change="handleCurrentChange">
							<el-table-column label="分组名称" prop="name" show-overflow-tooltip />
							<el-table-column label="24小时订单数" prop="rule_num" show-overflow-tooltip />
							<el-table-column label="用户数量" prop="user_num" show-overflow-tooltip />
							<el-table-column label="操作" fixed="right">
								<template #default="{ row }">
									点击选择
								</template>
							</el-table-column>
						</el-table>
					</div>
					<div class="flex mt-4 justify-end">
						<pagination v-model="pager" @change="getLists" />
					</div>
				</el-card>
			</div>
		</popup>
	</div>
</template>

<script lang="ts" setup name="goodsEdit">
	import Popup from '@/components/popup/index.vue'
	import type { PropType } from 'vue'
	import { usePaging } from '@/hooks/usePaging'
	import { apiUserGroupLists,apiSetUserGroup } from '@/api/user_group'
	import feedback from '@/utils/feedback'
	import { isEmpty } from 'lodash-es'

	defineProps({
		dictData: {
			type: Object as PropType<Record<string, any[]>>,
			default: () => ({})
		}
	})
	const emit = defineEmits(['success', 'close'])
	const popupRef = shallowRef<InstanceType<typeof Popup>>()


	// 弹窗标题
	const popupTitle = computed(() => {
		return '用户分组'
	})

	// 查询条件
	const queryParams = reactive({
	})

	// 表单数据
	const formData = reactive({
		user_id: '',
		group_id: 0,
	})

	// 选中数据
	const currentRow = ref()

	// 表格选择后回调事件
	const handleCurrentChange = (val : string) => {
		currentRow.value = val
	}

	// 分页相关
	const { pager, getLists, resetParams, resetPage } = usePaging({
		fetchFun: apiUserGroupLists,
		params: queryParams
	})


	// 提交按钮
	const handleSubmit = async () => {
		if (!isEmpty(currentRow.value)){
			formData.group_id = currentRow.value.id;
		}
		await apiSetUserGroup(formData)
		popupRef.value?.close()
		emit('success')
	}

	//打开弹窗
	const open = () => {
		popupRef.value?.open()
	}

	// 关闭回调
	const handleClose = () => {
		emit('close')
	}

	const setFormData = async (data : Record<any, any>) => {
		formData.user_id = data.user_id;
	}

	defineExpose({
		open,
		setFormData,
	})
	getLists()
</script>